package pipe

import (
	"gitee.com/injoyai/goutil/crypt/aes"
	"gitee.com/injoyai/goutil/g"
	"gitee.com/injoyai/goutil/net/conn/v2"
	"gitee.com/injoyai/goutil/oss/io"
	"log"
)

// WriteWithBase64 数据通讯加密,通道客户端服务端的发送数据函数
func WriteWithBase64(req []byte) []byte {
	req = []byte(g.EncodeBase64(req))
	return io.WriteWithDefault(req)
}

// ReadWithBase64 数据通讯解密,通道客户端服务端的读取数据函数
func ReadWithBase64(c *io.Client) (bytes []byte, err error) {
	bytes, err = io.ReadWithDefault(c)
	if err != nil {
		return nil, err
	}
	if len(bytes) > 4 {
		bytes = bytes[2 : len(bytes)-2]
	}
	return g.DecodeBase64(string(bytes))
}

func NewWriteAESCBC(key []byte, iv ...[]byte) func([]byte) []byte {
	return func(req []byte) []byte {
		req, _ = aes.EncryptCBC(req, key, iv...)
		return io.WriteWithDefault(req)
	}
}

func NewReadAESCBC(key []byte, iv ...[]byte) func(c *io.Client) (bytes []byte, err error) {
	return func(c *io.Client) (bytes []byte, err error) {
		bytes, err = io.ReadWithDefault(c)
		if err != nil {
			return nil, err
		}
		return aes.DecryptCBC(bytes, key, iv...)
	}
}

// BeforeWithServer 通道服务的前置操作,打印客户端连接信息
func BeforeWithServer(c *conn.Conn) error {
	log.Printf("[信息][%s] 新的通道客户端连接\n", c.GetKey())
	return nil
}

// PrintWithClient 通道客户端打印函数
func PrintWithClient(s string, msg *io.Message) {
	log.Printf("[%s][client][%s] %s\n", s, msg.Key(), msg.String())
}

// PrintWithServer 通道服务端打印函数
func PrintWithServer(s string, msg *conn.Message) {
	log.Printf("[%s][server][%s] %s\n", s, msg.Key(), msg.String())
}
